<?

	require_once('lib/OwnedObject.php');

	define(NEWS_STATUS_ACTUAL, 		1);
	define(NEWS_STATUS_ARCHIVE,		2);

	class News extends OwnedObject{
			protected $modelName = 'News';
			protected $status=NEWS_STATUS_ACTUAL;
			protected $title;
			protected $announce;
			protected $content='';

			public static function Install() {
                    OwnedObject::Install();
					$query=sprintf("CREATE TABLE `News` (
									`Id` INT( 32 ) unsigned NOT NULL ,
									`title` VARCHAR(255) ,
									`announce` VARCHAR(1023) ,
									`content` TEXT ,
									`status` INT( 4 ) NOT NULL ,									
									PRIMARY KEY ( `Id` ),
									FOREIGN KEY (`Id`) REFERENCES `Object`(`id`) ON DELETE CASCADE
									) ENGINE=INNODB DEFAULT CHARSET=utf8;
								");
					mysql_query($query);

					$query = sprintf("INSERT INTO `ObjectType` SET `name` = '%s'", strval(__CLASS__));
                        mysql_query($query);
					echo "News installed\n";
			}

			public function Load() {
                        parent::Load();

                        $query = sprintf("SELECT
												`title`, `announce`, `content`, `status`
										FROM
											`News`
										WHERE
											`Id` =%d", $this->id);
                        $res = mysql_query($query);
                        $row = mysql_fetch_array($res);

                        $this->title = $row[0];
                        $this->announce = $row[1];
                        $this->content = $row[2];
                        $this->status = $row[3];
			}

			public function AsSource($otherName = 'News'){
						$result = parent::AsSource($otherName);

						$result -> Attribute('title',$this->title);
						$result -> Attribute('status',$this->status);

						$content = new XmlSource('content',$this->content);
						$announce = new XmlSource('announce',$this->announce);

						
						$result -> MountSource($announce);
						$result -> MountSource($content);

						return $result;
			}

			public function Content($newContent=false) {
                        if($newContent)
                                $this->content = $newContent;
                        return $this->content;
            }

			public function Announce($newAnnounce=false) {
                        if($newAnnounce)
                                $this->announce = $newAnnounce;
                        return $this->announce;
            }
            
			public function Title($newTitle=false) {
                        if($newTitle)
                                $this->title = $newTitle;
                        return $this->title;
            }            

			public function RegisterObject(){
						$obj_id= parent::RegisterObject();
						$query=sprintf("INSERT INTO
												`News` ( `Id` , `title` , `announce` , `content`, `status` )
											VALUES (%d, '%s', '%s', '%s', %d)
							", $obj_id, mes($this->title), mes($this->announce), $this->content, $this->status);
						mysql_query($query);
			}


			public function Save(){
						if($this->id<1){
							$this->RegisterObject();
						}
						else{
							if($this->answer) $this->status=QUESTION_STATUS_ANSED;
							$query=sprintf("UPDATE `News`
											SET
												  `title` = '%s',
												  `announce` = '%s',
												  `content`= '%s',
												  `status`= %d
											WHERE `Id`=%d", mes($this->title), mes($this->announce), $this->content, $this->status, $this->id);
							mysql_query($query);
						}
			}


			public function Remove(){
				$query=sprintf("DELETE FROM `News` WHERE Id=%d",$this->id);
				mysql_query($query);
				parent::Remove();
			}
			

			public static function CreateNewsFish($num){
				$act = array('Внимание-внимание!!!', 'Уважаемые дамы и гоподЫ!');
				$time = array('Вчера ', 'Сегодня ', 'Год назад ');
				$subs = array('конь ','собака ','порталл ','погода ','кошка ');
				$verbs = array('мурлыкнула ','гавкнула ','тикнула ', 'прыг ', 'не смог прийти на совещание');
				$prefix = array('О ', 'Про ', 'Новость о ');


				$ac = count($act)-1;
				$tc = count($time)-1;
				$sc = count($subs)-1;
				$vc = count($verbs)-1;
				$pc = count($prefix)-1;

				for($i=0;$i<$num;$i++){
					sleep(1);
					$s = rand(0,$sc);
					$v = rand(0,$vc);
					$title=$prefix[rand(0,$pc)].$subs[$s];
					$announce = $subs[$s].$verbs[$v];
					$content = '';
					$content .= $act[rand(0,$ac)]; $content = '<h3>'.$content.'</h3>';
					$content .= '<p>'.$time[rand(0,$tc)].$subs[$s].$verbs[$v].'</p>';


					$nm = new News();
					$nm->Title($title);
					$nm->Announce($announce);
					$nm->Content($content);
					$nm->Save();
					
					$new_path = $_SERVER['DOCUMENT_ROOT'].'/media/news/'.$nm->Id();
					mkdir($new_path);
					$new_path.='/title_news.jpg';
					
					copy($_SERVER['DOCUMENT_ROOT'].'/images/pic-news.jpg', $new_path);					
					$im = imagecreatefromjpeg($new_path);
					imagestring($im,10,3,3,$nm->Title(),imagecolorallocate($im, 255, 0, 0));
					imagejpeg($im,$new_path);					
					
				}
			}
			
			//Новости по количеству
			public static function NewsByCount($num=8,$offset=0){
					$query = sprintf("SELECT n.`Id` 
					FROM `News` n, `Object` o 
					WHERE n.`Id`=o.`id` and `status`=%d ORDER BY o.`created` DESC
					LIMIT %d, %d", NEWS_STATUS_ACTUAL, $offset, $num);
					$parse = mysql_query($query);

					$news_list = new XmlSource('News-list');
					while($result = mysql_fetch_assoc($parse)){
						
						$n_id = $result['Id'];
						$news = new News($n_id);
						$news->Load();
						$news_list->MountSource($news->AsSource());
					}
					
					//mount pages
					$query = sprintf("SELECT count(1) FROM `News`
					WHERE `status`=%d", NEWS_STATUS_ACTUAL);
					$res = mysql_query($query);
					$row = mysql_fetch_row($res);
					$news_count = $row[0];
					
					$pages_count = (int)$news_count/$num;
					$selected_page = (int)$offset / $num + 1;
					
					$pages = new XmlSource('pages');
					for($i=1; $i<=$pages_count; $i++){
						$p_link = new XmlSource('page');
						$p_link->Attribute('num', $i);
						if($i == $selected_page) $p_link->Attribute('selected', 'selected');
						$pages->MountSource($p_link);
					}
					
					$news_list->MountSource($pages);

					return $news_list;
			}			

	}

?>